package java0.gateway.router;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 轮询算法  参考 Ribbon
 *
 * @author L.xf
 * @date 2021/9/28
 */
public class RoundHttpEndpointRouter implements HttpEndpointRouter {

    private AtomicInteger nextServerCyclicCounter = new AtomicInteger(0);


    @Override
    public String route(List<String> endpoints) {
        int size = endpoints.size();
        int nextServerIndex = incrementAndGetModulo(size);
        return endpoints.get(nextServerIndex);

    }

    // 利用CAS
    private int incrementAndGetModulo(int size) {
        for (; ; ) {
            int current = nextServerCyclicCounter.get();
            int next = (current + 1) % size;
            if (nextServerCyclicCounter.compareAndSet(current, next)) {
                return next;
            }

        }
    }
}
